from tornado.web import authenticated
from common.BaseHandler import BaseHandler
from common.Models import Author
from utils.DateHandler import DateHandler


class LoginHandler(BaseHandler):
    def get(self):
        data = self.get_params()
        self.page_next = data.get("next", None)
        self.render("management/login.html")

    def post(self):
        result = self.result(msg="登录失败！")
        try:
            data = self.get_body()
            username = self.data_null(data, "username", "请输入账号！")
            password = self.data_null(data, "password", "请输入密码！")
            author = self.session.query(Author).filter_by(phone=username, password=password, is_delete=0).first()
            if author:
                print(author.name)
                print(self.page_next)
                self.set_secure_cookie("author_id", str(author.id))
                author.last_login_time = DateHandler.now()
                self.session.commit()
                result["status"] = 1
                result["msg"] = "登录成功！"
                result["data"] = {
                    "href": self.page_next if self.page_next else "/manage/index",
                    "userName": author.name
                }
            else:
                result["msg"] = "用户名或密码不正确！"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, msg="登录失败！")
        self.write(result)


class LogoutHandler(BaseHandler):
    @authenticated
    def get(self):
        self.clear_cookie("author_id")
        self.redirect("/author/login")

